# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class ScrapyReadbookDomePipeline:
    def open_spider(self, spider):
        self.fp=open("./book.json","w",encoding="utf-8")
        print("爬虫开始了")
    def process_item(self, item, spider):
        self.fp.write(str(item))
        return item
    def close_spider(self, spider):
        self.fp.close()
        print("爬虫结束了")
# import urllib.request
# class imgsDownloadPipeline:
#     def process_item(self, item, spider):
#         url=item["src"]
#         name=item["name"]
#         headers={
#             "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
#         }
#         urllib.request.urlretrieve(url=url,filename="./bookimgs/"+name+".jpg",headers=headers)
#         print("图片下载成功")
import pymysql
class MysqlPipeline:
    def open_spider(self, spider):
        self.conn=pymysql.connect(
            host="localhost",
            port=3306,user="root",
            password="17884873770",
            database="spider01",
            charset="utf8")
        self.cursor=self.conn.cursor()
        print("数据库连接成功")

    def process_item(self, item, spider):
        name=item["name"]
        author=item["author"]
        src=item["src"]
        sql='insert into book(name,src,author) values("{}","{}","{}")'.format(name,src,author)
        self.cursor.execute(sql)
        self.conn.commit()
        return item
    def close_spider(self,spider):
        self.cursor.close()
        self.conn.close()
